//
//  ProblemViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/9/9.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "ProblemViewController.h"
#import "UIColor+Hex.h"
#import "MBProgressHUD+MJ.h"
#import <AliyunOSSiOS/OSSService.h>
#import "AFHTTPRequestOperationManager.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapFoundationKit/AMapServices.h>
#import <AMapLocationKit/AMapLocationKit.h>
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试

@interface ProblemViewController ()
@property NSMutableArray *imageUrl;
@property float lat;
@property float lon;
@end

@implementation ProblemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.firstPro = @"";
    self.note_text .delegate = self;
    
     _imageUrl = [[NSMutableArray alloc] init];
    //[self.limitBtn setBackgroundColor:[UIColor colorWithHexString:@"#ff7e00"]];
    
    [self.limitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateNormal];
     [self.limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#55ff7e00"]] forState:UIControlStateSelected];
    
    [self.limitBtn addTarget:self action:@selector(limitClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.images = @[self.imageView1,self.imageView2,self.imageView3];
    self.photo_view1.tag = 0;
    self.photo_view2.tag = 1;
    self.photo_view3.tag = 2;
    
    [self.photo_view1 addTarget:self action:@selector(callActionSheetFunc:) forControlEvents:UIControlEventTouchUpInside];
    [self.photo_view2 addTarget:self action:@selector(callActionSheetFunc:) forControlEvents:UIControlEventTouchUpInside];
    [self.photo_view3 addTarget:self action:@selector(callActionSheetFunc:) forControlEvents:UIControlEventTouchUpInside];
    
    [self initPickView];
    [self initCompleteBlock];
    [self configLocationManager];
}

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    //[self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    //[self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    //进行单次定位请求
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}
- (void)initCompleteBlock
{
    __weak ProblemViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            //如果为定位失败的error，则不进行annotation的添加
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        //得到定位信息，添加annotation
        if (location)
        {
            _lat = location.coordinate.latitude;
            _lon = location.coordinate.longitude;
        }
    };
}

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)button_click:(id)sender {
    int pop = self.popCount;
    UIViewController *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - pop];
    [self.navigationController popToViewController:vc animated:YES];
}
- (IBAction)view_touch:(id)sender {
    [self.view endEditing:YES];  
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self.note_text resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}

/**
 @ 调用ActionSheet
 */
- (void)callActionSheetFunc:(UIControl *) controll{
    
    if (self.add_image_pos != controll.tag) {
        return;
    }
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择",  nil];
    }else{
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消"destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",  nil];
    }
    
    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else {
            if (buttonIndex == 2) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //获得的图片
    UIImageView *imageView = self.images[self.add_image_pos];
    imageView.image = image;
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    [self uploadImage:imgData];
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)showTimeView:(id)sender {
    
    UIView *timeView = [self.view viewWithTag:111];
    if (timeView.hidden) {
        timeView.hidden = NO;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            UIPickerView *pickView1 = [self.view viewWithTag:10101];
            // [pickView1 selectRow:0 inComponent:0 animated:NO];
            // [pickView1 selectRow:0 inComponent:1 animated:NO];
            [self pickerView:pickView1 didSelectRow:0 inComponent:0];
            [self pickerView:pickView1 didSelectRow:0 inComponent:1];
            timeView.frame = CGRectMake(0, ScreenHeight - 260, ScreenWidth, 260);
        }];
        
    }else{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 260);
            timeView.hidden = YES;
        }];
        
        
    }
}


-(NSInteger)initData{
    
    NSInteger result = 0;
    
    
    self.dataArray = @[@"用户",@"支装",@"干线",@"厂家",@"外包完好货损",@"不可抗因素"];
    
    NSArray * array1 = @[@"其他",@"更改送装地址",@"用户电话错",@"联系不上",@"用户改约"];
    NSArray * array2 = @[@"其他",@"送装不及时",@"操作疏失",@"服务能力不足"];
    NSArray * array3 = @[@"其他",@"超区提货",@"物流点少货",@"干线超期报到货",@"干线超时到货",@"干线分两次发货",@"信息录入错误",@"干线货损",@"垫付运费",@"过路车"];
    NSArray * array4 = @[@"其他",@"发货早",@"发货错",@"少发货"];
    NSArray * array5 = @[@"其他",@"外包完好货损"];
    NSArray * array6 = @[@"其他",@"天气原因"];
    self.secondDataArray = array1;
    self.dataArray2 = @[array1,array2,array3,array4,array5,array6];
    return result;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    NSLog(@"numberOfComponentsInPickerView");
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSLog(@"numberOfRowsInComponent");
    if (component == 0) {
        return self.dataArray.count;
    }else{
        return self.secondDataArray.count;
    }
    
    
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (component == 0) {
        return self.dataArray[row];
    }else{
        return self.secondDataArray[row];
    }
    
    
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    
    if (component == 0) {
        self.secondDataArray =  self.dataArray2[row];
        self.firstPro = self.dataArray[row];
        [pickerView reloadComponent:1];
    }else{
        self.secondPro = self.secondDataArray[row];
    }
    
}

//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
//{
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12.0f, 0.0f, [pickerView rowSizeForComponent:component].width - 12, [pickerView rowSizeForComponent:component].height)] ;
//
//    label.text = self.dataArray[component][row];
//    label.backgroundColor = [UIColor clearColor];
//    label.textColor = [UIColor blackColor];
//    //[label setTextAlignment:UITextAlignmentCenter];
//    return label;
//}



- (void)initPickView{
    //初始化数据
    [self initData];
    
    UIView *dialogView = [[UIView alloc]initWithFrame: CGRectMake(0, ScreenHeight, ScreenWidth, 260)];
    dialogView.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    dialogView.tag = 111;
    dialogView.hidden = YES;
    
    UIButton * cancle = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 60, 30)];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    cancle.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [cancle addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * ok = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 70, 10, 60, 30)];
    ok.tag = 55;
    ok.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [ok setTitle:@"确定" forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [ok addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIPickerView *pickView1 = [[UIPickerView alloc]initWithFrame:CGRectMake(10, 40,(ScreenWidth - 20) , 200)];
    //pickView1.backgroundColor = [UIColor greenColor];
    pickView1.tag = 10101;
    
    
    
    
    pickView1.showsSelectionIndicator = YES;
    
    
    
    [dialogView addSubview:cancle];
    [dialogView addSubview:ok];
    [dialogView addSubview:pickView1];
    
    [self.view addSubview:dialogView];
    
    pickView1.dataSource = self;
    pickView1.delegate = self;
    
    
    
    
   // [pickView1 selectRow:0 inComponent:0 animated:NO];
   // [pickView1 selectRow:0 inComponent:1 animated:NO];
    //[self pickerView:pickView1 didSelectRow:0 inComponent:0];
    //[self pickerView:pickView1 didSelectRow:0 inComponent:1];
   
    
}

-(void)dialogBtn:(UIButton *) button{
    [self showTimeView:button];
    if (button.tag == 55) {
        //  self.oppointBtn.titleLabel.text = [NSString stringWithFormat:@"%@年%@%@",self.myear,self.monthDay,self.mTime];
        
        [self.problemBtn setTitle:[NSString stringWithFormat:@"%@-%@",self.firstPro,self.secondPro] forState:UIControlStateNormal];
    }
}


-(void)uploadImage:(NSData *)img{
    
    
    
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OOS_KEY_ID  secretKey: OOS_KEY_SCERET];
    
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:@"http://oss-cn-shanghai.aliyuncs.com" credentialProvider:credential];
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    // 必填字段
    put.bucketName = OOS_KEY_BUCKET;
    
    NSString *filePath = [NSString stringWithFormat:@"%@.png",[self getUniqueStrByUUID]];
    put.objectKey = filePath;
    
     [_imageUrl addObject:[NSString stringWithFormat:@"http://%@.oss-cn-shanghai.aliyuncs.com/%@",OOS_KEY_BUCKET,filePath]];
    // put.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
    put.uploadingData = img; // 直接上传NSData
    
    // 可选字段，可不设置
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    // 以下可选字段的含义参考： https://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
    // put.contentType = @"";
    // put.contentMd5 = @"";
    // put.contentEncoding = @"";
    // put.contentDisposition = @"";
    
    // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil]; // 可以在上传时设置元信息或者其他HTTP头部
    
    [MBProgressHUD showMessage:@"上传图片"];
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {
        
        if (!task.error) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                NSLog(@"上传图片结果22");
                [MBProgressHUD hideHUD];
                self.add_image_pos++;
                if (self.add_image_pos < 3) {
                    UIImageView *addimage = self.images[self.add_image_pos];
                    addimage.image = [UIImage imageNamed:@"add_image"];
                }
                NSLog(@"upload object success111!");
            });
            
            NSLog(@"upload object success222!");
        } else {
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                
                [MBProgressHUD hideHUD];
                UIImageView *addimage = self.images[self.add_image_pos];
                addimage.image = [UIImage imageNamed:@"add_image"];
                [_imageUrl removeObjectAtIndex:_add_image_pos];
                NSLog(@"upload object success111!");
            });
        }
        
        
        return nil;
    }];
}
- (NSString *)getUniqueStrByUUID
{
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    
    //get the string representation of the UUID
    
    NSString    *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString ;
    
}

-(void)limitClick{

    if ([self.firstPro isEqualToString:@""]) {
        [MBProgressHUD showError:@"请选择问题类型"];
    }else if (_imageUrl.count== 0 || _imageUrl .count < 2) {
        [MBProgressHUD showError:@"请上传至少两张照片"];
    }else{
        NSString *userId = [UserDefaultUtil getUserId];
        
        
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:userId forKey:@"identifier"];
        [dic setObject:_serviceNo forKey:@"serviceNo"];
        [dic setObject:_firstPro forKey:@"type"];
        [dic setObject:_secondPro forKey:@"category"];
        [dic setObject:_note_text.text forKey:@"notes"];
        
        [dic setObject:[NSString stringWithFormat:@"%f",_lon] forKey:@"lon"];
        [dic setObject:[NSString stringWithFormat:@"%f",_lat] forKey:@"lat"];
        [dic setObject:_imageUrl forKey:@"photos"];
        
        
        HttpReauestParam *param = [[HttpReauestParam alloc] initWithData:@"order_problem_operator" content:[self dictionaryToJson:dic] urlType:0];
        AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
        [MBProgressHUD showMessage:@"提交数据"];
        manage.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
            
            [MBProgressHUD hideHUD];
            
            if ([data[@"success"] boolValue]) {
                [MBProgressHUD showSuccess:@"提交成功"];
                
                int pop = self.popCount;
                UIViewController *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - pop];
                [self.navigationController popToViewController:vc animated:YES];
            }else{
                [MBProgressHUD showError:data[@"errorMsg"]];
            }
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"网络连接失败"];
        }];
    }
    
    
    
}

-(NSString*)dictionaryToJson:(id)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

@end
